import React from 'react';
import { Link } from 'react-router-dom';
import { observer, inject } from 'mobx-react';

import 'fabric';

import $ from 'zepto';

import { Icon, message, Button, Modal, Input, Select } from 'antd';
const { Option } = Select;

import { PageEventType } from '../../utils/PageEventType'

import '../ShowPage/index.scss'
import './index.scss'
import service from '../../service';

@inject('createStore')
@inject('baseStore')
@observer
class ShowPage extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			visible: true,
			side_show: false,
			moveCanvas: false,
			dragIning: false,
			canvas_orign: {
				width: 1398,
				height: 423
			},
			show_img: false,
			show_img_url: '',
			show_video: false,
			show_video_url: '',
			bgImgList: [{
				ImgUrl: 'http://www.besteasylearn.com/pic/canvas_bg/米_1200x600.png',
				Width: 1200,
				Height: 600
			}, {
				ImgUrl: 'http://www.besteasylearn.com/pic/canvas_bg/田_1200x600.png',
				Width: 1200,
				Height: 600
			}],
			bgImgActivedIndex: 0,
			canvasMyMod: 0, // 左侧进入模式   0.展示模式  1.单点击编辑  2.拖放  
			curRightActivedItem: null,  //右侧当前激活  用于单击编辑框

			currentWordImgList: [], //点击后赋值  并显示出来 用先拖放
			activeRightListIndex: -1,

			show_bg_select: false,

			fu_shi_list: [],

			fu_shi_sub_list: [],

			bgList: [{
				id: "10",
				pid: '',
				name: '临摹纸',
				children: [{
					id: "10_01",
					pid: '10',
					name: '临摹纸01',
					active: true,
					ImageURL: '/create/11.png'

				}, {
					id: "10_02",
					pid: '10',
					name: '临摹纸02',
					active: false,
					ImageURL: '/create/2_1.png'
				}],
				active: true
			}, {
				id: "11",
				pid: '',
				name: '横幅',
				children: [{
					id: "11_01",
					pid: '11',
					name: '横幅53x16',
					active: false,
					ImageURL: '/create/2_1.png'
				}, {
					id: "11_02",
					pid: '11',
					name: '三尺横幅',
					active: false,
					ImageURL: '/create/2_1.png'
				}],
				active: false
			}],

			ShuJiaList: [],

			formData: {
				"DirectoryId": "",
				"DirectoryName": "",
				"ImageName": "",
				"ImageURL": "",
				"CalligrapherId": "",
				"CalligrapherName": "",
				"PageFormatId": "",
				"PageFormatName": "",
				"ParentFormatId": "",
				"PageFormatName": "",
				"WordId": "",
				"WordNum": "",
				"WordNumName": "",
				"JsonStr": ""
			},
			currenCanvasBgImageURL: '',
			id: '',
			center_then_move_top: 0,
			center_then_move_left: 0,
			LoadFormData: {

			},
			fuShiIndex: 0,
			fuShiSubIndex: 0
		};

		this._canvas = null;
		this.container = null;
		this.id = "";
	}



	loadFromJsonInit = (res) => {

		var that = this;

		service.GetFuShiEntityById("ad89a04b-3991-40d2-8025-961e1ded5ad4").then(subFuShiEntity => {
			console.log(subFuShiEntity, "===========GetFuShiEntityById========");

			var that = this;

			var url = that.props.baseStore.GetFinalImageUrl(subFuShiEntity.ImageURL);

			//只为了拿个宽高
			fabric.Image.fromURL(url, function (oImg) {

				that._canvas.setWidth(oImg._element.width);
				that._canvas.setHeight(oImg._element.height);

				that.setState({
					canvas_orign: {
						width: oImg._element.width,
						height: oImg._element.height
					}
				});

				that._canvas.setWidth(oImg._element.width);
				that._canvas.setHeight(oImg._element.height);
				that._canvas.loadFromJSON(res.JsonStr);

				setTimeout(() => {
					that._canvas.selections = false;

					that._canvas.preserveObjectStacking = true;
				}, 1000);




			});
		})

		if (this.id == '') {
			$(".canvas-container").css({
				// left: container.width / 2 - this.getDomRealData($canvas_container).css_width / 2,
				right: 100,
				top: '50%',
				// top: container.height / 2 - this.getDomRealData($canvas_container).css_height / 2
				transform: "translateY(-50%)"
			});
		} else {
			$(".canvas-container").css({
				// left: container.width / 2 - this.getDomRealData($canvas_container).css_width / 2,
				left: '50%',
				top: '50%',
				// top: container.height / 2 - this.getDomRealData($canvas_container).css_height / 2
				transform: "translate(-50%,-50%)"
			});
		}
	}

	loadImgUrl = (url) => {
		var that = this;
		fabric.Image.fromURL(url, function (oImg) {

			that._canvas.setWidth(oImg._element.width);
			that._canvas.setHeight(oImg._element.height);

			that.setState({
				canvas_orign: {
					width: oImg._element.width,
					height: oImg._element.height
				}
			});


			oImg.preserveObjectStacking = true;
			oImg.selectable = false;

			oImg.crossOrigin = 'anonymous';

			that._canvas.add(oImg);

			that.canvasZoomDirect(1);

		});
	}


	initCanvas = (url) => {
		var that = this;
		//url = url || this.props.baseStore.getPicInnerStaticPreUrl + "/create/11.png";
		if (this.id.length > 0) {
			service.GetFuShiEntityById(this.id).then(res => {
				console.log(res, "===========GetFuShiEntityById========");

				var that = this;

				that.setState({
					LoadFormData: res
				})

			});
		} else {
			that.loadImgUrl(url);
		}


		var start_pos = {
			x: 0,
			y: 0
		};

		var $canvas_container = $(".canvas-container");

		this.container = {
			width: 1920, //侧边
			height: $('.ShowPage_Main').height()
		}

		var container = this.container;

		this.setState({
			center_then_move_top: 0,
			center_then_move_left: 0,
		});
		if (this.id == '') {
			$(".canvas-container").css({
				// left: container.width / 2 - this.getDomRealData($canvas_container).css_width / 2,
				left: 'initial',
				right: 100,
				top: '50%',
				// top: container.height / 2 - this.getDomRealData($canvas_container).css_height / 2
				transform: "translateY(-50%)"
			});

		} else {
			$(".canvas-container").css({
				// left: container.width / 2 - this.getDomRealData($canvas_container).css_width / 2,
				left: '50%',
				top: '50%',
				// top: container.height / 2 - this.getDomRealData($canvas_container).css_height / 2
				transform: "translate(-50%,-50%)"
			});
		}



		var container_pos = {
			x: $('.canvas-container').position().left,
			y: $('.canvas-container').position().top
		}






		// that._canvas.on('selection:created', function (options) {
		// 	console.log(33);
		// 	options.e.stopPropagation();
		// 	options.e.preventDefault();
		// });

		//写入字
		that._canvas.on('mouse:up', function (options) {

			options.e.preventDefault();
			options.e.stopPropagation();

			console.log(options, "=====options========");

			var pos = {
				x: options.pointer.x,
				y: options.pointer.y
			}

			var evt_pageX = options.e.pageX;
			var evt_pageY = options.e.pageY;

			var item = that.state.freeActiveItem;

			if (item != null) {

				var url = that.props.baseStore.GetFinalImageUrlForCanvas(item.ImageURL);

				fabric.Image.fromURL(url, function (oImg) {

					oImg.width = oImg._element.width;
					oImg.height = oImg._element.height;

					oImg.top = pos.y - 150;
					oImg.left = pos.x - 150;

					console.log(`${oImg.top}_${oImg.left}`);

					oImg.preserveObjectStacking = true;

					oImg.scaleX = oImg.width / 300;
					oImg.scaleY = oImg.height / 300;

					oImg.crossOrigin = 'anonymous';

					oImg.selectable = true;

					that._canvas.add(oImg);

				});

				that.setState({
					freeActiveItem: null
				})


			}

			return false;
		})
	}


	componentDidMount() {

		var that = this;


		var id = this.props.match.params.id || '';
		that['id'] = id;

		// alert(id);


		if (id == '') {
			that.setState({
				side_show: true
			})
		} else {
			that.setState({
				id: id
			})
		}



		this.props.baseStore.topHeader.show = true;
		this.props.baseStore.topHeader.title = "自由创作";
		this.props.baseStore.topHeader.backTo = '/entry_04';

		var list = this.props.createStore.getRightListDirect();

		this.props.createStore.SetRightListDirect(list);

		service.GetShuJiaList().then(res => {
			console.log(res, "===========GetShuJiaList========");
			console.log(res.length, "===========list.length========");
			that.setState({
				ShuJiaList: that.state.ShuJiaList.concat(res)
			});
		})

		var canvas = this._canvas;
		var moveCanvas = this.moveCanvas;

		this._canvas = new fabric.Canvas('canvas', {
			// isDrawingMode: true,
			// width: 1400,
			// height: 600,

			width: 1211,
			height: 731,
			selections: true
			// backgroundColor: '#D6F8FF'
		});

		// 筆刷樣式
		this._canvas.freeDrawingBrush.color = 'lightskyblue'
		this._canvas.freeDrawingBrush.width = 2

		this._canvas.selection = false;
		this._canvas.preserveObjectStacking = false;
		// var url = "http://www.besteasylearn.com/pic/create/2_1.png";
		var url = this.props.baseStore.getPicInnerStaticPreUrl + "/create/11.png";
		// this._canvas.setBackgroundImage(url, this._canvas.renderAll.bind(this._canvas));











		if (this.id == '') {
			service.GetFuShiList().then(res => {
				console.log(res, "===========GetShuJiaList========");
				console.log(res.length, "===========list.length========");
				that.setState({
					fu_shi_list: res
				});

				service.GetFuShiChildListById(res[1].DirectoryID).then(res => {
					console.log(res, "===========GetShuJiaList========");
					console.log(res.length, "===========list.length========");
					that.setState({
						fu_shi_sub_list: res
					});

					var url = that.props.baseStore.GetFinalImageUrlForCanvas(res[0].ImageURL);

					//写入背景图片
					that.setState({
						currenCanvasBgImageURL: url,
						fuShiIndex: 1,
						fuShiSubIndex: 0
					});

					that.initCanvas(url);
				})
			})


		} else {

			service.GetWordLinmoEntityById(this.id).then(res => {
				console.log(res, "===========GetWordLinmoEntityById========");

				res.PageFormatId = "ad89a04b-3991-40d2-8025-961e1ded5ad4";


				that.setState({
					LoadFormData: res
				})
				that.loadFromJsonInit(res);
			});


		}



		document.ondragover = function (ev) {
			ev.preventDefault();
		};

		document.querySelector(".canvas_can_drag") && document.querySelector(".canvas_can_drag").addEventListener('click', function () {


			var mask = `<div class="canvas_mask"></div>`;

			if ($('.canvas_mask').length == 0) {
				$(".canvas-container").append($(mask));
			} else {
				$('.canvas_mask').remove();
				return;
			}

			$('.canvas_mask').unbind().bind(PageEventType.moveEvent, function (evt) {
				if (moveCanvas) {
					var evt_pageX = evt.pageX || evt.touches[0].pageX;
					var evt_pageY = evt.pageY || evt.touches[0].pageY;

					$(".canvas-container").css({
						left: container_pos.x / window.scaleX + (evt_pageX - start_pos.x),
						top: container_pos.y / window.scaleY + (evt_pageY - start_pos.y),
						transform: "none"
					});
				}
			}).bind(PageEventType.startEvent, function (evt) {

				console.log(evt, "===========mousedown.evt=============");

				moveCanvas = true;

				var evt_pageX = evt.pageX || evt.touches[0].pageX;
				var evt_pageY = evt.pageY || evt.touches[0].pageY;

				start_pos = {
					x: evt_pageX,
					y: evt_pageY
				}

				container_pos = {
					x: $(".canvas-container").position().left,
					y: $(".canvas-container").position().top
				}


			}).bind(PageEventType.endEvent, function (evt) {
				moveCanvas = false;
				$('.canvas_mask').remove();
			}).bind(PageEventType.cancelEvent, function (evt) {
				moveCanvas = false;
				$('.canvas_mask').remove();
			});

			$(window).on(PageEventType.endEvent, function (e) {
				moveCanvas = false;
				$('.canvas_mask').remove();
			})


			that.setState({
				side_show: false
			})




		});

		$('.ShowPage_Main')[0].addEventListener('mousewheel', function (e) {
			var direction = e.deltaY > 0 ? 'down' : 'up'
			var num = direction == "up" ? 0.1 : -0.1
			that.canvasZoom(num);
		})

		$('.ShowPage_Main').click(function (e) {
			console.log('window.click');

			if (e.target.className != "upper-canvas ") {
				that._canvas.discardActiveObject();
				that._canvas.renderAll();
			}

		});


		this.bindPadKey();


	}

	componentWillUnmount = () => {
		this.setState = (state, callback) => {
			return;
		};
	}

	bindPadKey = () => {
		var that = this;
		//向上
		window.listenerNativeCode('19', function (code) {
			that.moveCanvasHandler(1);
		})

		//向下
		window.listenerNativeCode('20', function (code) {
			that.moveCanvasHandler(3);
		})

		//向左
		window.listenerNativeCode('21', function (code) {
			that.moveCanvasHandler(4);
		})

		//向右
		window.listenerNativeCode('22', function (code) {
			that.moveCanvasHandler(2);
		})



		//放大
		window.listenerNativeCode('24', function (code) {
			that.zoomToForPhysicalButton(1);
		})

		//缩小
		window.listenerNativeCode('25', function (code) {
			that.zoomToForPhysicalButton(-1);
		})
	}

	handleClick = () => {

		this.setState({
			side_show: !this.state.side_show
		})

	}

	getDomRealData = (selector) => {
		var param = {
			css_width: parseFloat($(selector).css('width').replace('px', '')),
			css_height: parseFloat($(selector).css('height').replace('px', ''))
		};
		return param;
	}

	zoomToForPhysicalButton = (num) => {

		var arr = [50, 75, 90, 100, 120];
		var curIndex = arr.indexOf(this.state.each_w_mm);

		if (num > 0) {
			curIndex = curIndex + 1;
			curIndex = curIndex > 5 ? 5 : curIndex;
			//放大
		} else {
			curIndex = curIndex - 1;
			curIndex = curIndex < 0 ? 0 : curIndex;
		}


		this.zoomToMM(arr[curIndex])
	}

	canvasZoom(num) {

		var zoom = this._canvas.getZoom();

		zoom += num;

		message.config({
			top: 100,
			duration: 1,
			maxCount: 1,
		});
		if (zoom > 1.7 || zoom < 0.5) {
			message.warning('超出最大或最小缩比例！');
			return;
		}

		this.canvasZoomDirect(zoom);

	}


	zoomToMM = (mm) => {
		// 计算出如果调成安世高10cm的绽放比例
		var my_px = WinHelper.mmToPx(mm);
		my_px = Math.round(my_px);
		console.log(my_px, "=======my_px=======");
		this.setState({
			each_w: my_px,
			each_w_mm: mm
		})
	}

	canvasZoomDirect(zoom) {
		this._canvas.setWidth(this.state.canvas_orign.width * zoom);
		this._canvas.setHeight(this.state.canvas_orign.height * zoom);
		this._canvas.setZoom(zoom);
		this.setCanvaWrapPosition();
	}

	setCanvaWrapPosition() {

		var that = this;
		var $canvas_container = $(".canvas-container");

		if (this.state.id == '') {
			$(this._canvas.wrapperEl).css({
				// top: that.container.height / 2 - this.getDomRealData($canvas_container).css_height / 2,
				top: '50%',
				// left: "50%",
				right: 100,
				transform: "translateY(-50%)"
			})
		} else {
			$(this._canvas.wrapperEl).css({
				// top: that.container.height / 2 - this.getDomRealData($canvas_container).css_height / 2,
				top: '50%',
				left: "50%",
				transform: "translate(-50%,-50%)"
			})
		}


	}

	canvasZoomIn = () => {
		this.canvasZoom(0.05)
	}

	canvasZoomOut = () => {
		this.canvasZoom(-0.05)
	}

	canvasClear = () => {

		var that = this;
		this._canvas.clear();

		//要把背景图画上去
		var url = this.props.baseStore.getPicInnerStaticPreUrl + "/create/2_1.png";

		url = this.state.currenCanvasBgImageURL;

		console.log(url, "canvasClear");

		that.initCanvas(url);

		// this._canvas.setBackgroundImage(url, this._canvas.renderAll.bind(this._canvas));

		//写入背景图片
		// fabric.Image.fromURL(url, function (oImg) {

		// 	that._canvas.setWidth(oImg._element.width);
		// 	that._canvas.setHeight(oImg._element.height);

		// 	oImg.preserveObjectStacking = true;
		// 	oImg.selectable = false;

		// 	oImg.crossOrigin = 'anonymous';

		// 	that._canvas.add(oImg);

		// });
	}

	canvasClearSelected = () => {

		var object = this._canvas.getActiveObject();
		this._canvas.remove(object);

	}

	canvasChangeBg = () => {


		var curBgImgIndex = this.state.bgImgActivedIndex;
		if (curBgImgIndex < this.state.bgImgList.length - 1) {
			this.setState({
				bgImgActivedIndex: curBgImgIndex + 1
			})
			curBgImgIndex = curBgImgIndex + 1;
		} else {
			this.setState({
				bgImgActivedIndex: 0
			})
			curBgImgIndex = 0
		}

		var curBgImgObj = this.state.bgImgList[curBgImgIndex];
		$(this._canvas.wrapperEl).css({
			backgroundImage: `url(${curBgImgObj.ImgUrl})`
		});
	}



	hideShowImg = () => {
		this.setState({
			show_img: false
		})
	}



	singleContainClick = (item, index) => {
		var that = this;
		console.log(item);
		// return false;


		if (this.state.canvasMyMod == 0) {
			// this.canvasClear();

			var that = this;

			this.props.createStore.SetCurrentWordItem(item);
			this.setState({
				activeRightListIndex: index
			})

		} else if (this.state.canvasMyMod == 1) {
			this.setState({
				curRightActivedItem: item
			});

			var mask = `<div class="canvas_click_position_drop_mask"></div>`;

			if ($('.canvas_click_position_drop_mask').length == 0) {
				$(".canvas-container").append($(mask));
			} else {

			}

			document.querySelector(".canvas_click_position_drop_mask").addEventListener('click', function (e) {


				//curRightActivedItem
				console.log(e, "点击画板");



				var item = that.state.curRightActivedItem;


				fabric.Image.fromURL(item.ImgUrl, function (oImg) {

					oImg.width = item['ImgWidth'] || 300;
					oImg.height = item['ImgHeight'] || 300;

					oImg.top = Math.floor(e.offsetY / 300) * 300;
					oImg.left = Math.floor(e.offsetX / 300) * 300;



					oImg.preserveObjectStacking = true;

					oImg.scaleX = oImg.width / 300;
					oImg.scaleY = oImg.height / 300;

					oImg.crossOrigin = 'anonymous';

					that._canvas.add(oImg);

				});

				// $('.canvas_click_position_drop_mask').remove();

			});

			document.querySelector(".canvas_click_position_drop_mask").addEventListener('click', function (e) {

			});

		}




	}

	DownLoadImg = () => {
		$('.img_for_show_create_img').click();
	}


	showVideo = (e, item) => {
		e.stopPropagation();

		this.setState({
			show_video: true,
			show_video_url: item
		})
	}

	closeVideo = () => {
		this.setState({ show_video: false })
	}

	moveCanvasHandler = (type) => {


		var top = this.state.center_then_move_top;
		var left = this.state.center_then_move_left;

		var changTop = 0;
		var changLeft = 0;
		if (type == 1) {
			changTop = -30;
		} else if (type == 2) {
			changLeft = 30;
		} else if (type == 3) {
			changTop = 30;
		} else if (type == 4) {
			changLeft = -30;
		}

		top = top + changTop;
		left = left + changLeft;

		this.setState({
			center_then_move_top: top,
			center_then_move_left: left
		});

		var topStr = '';
		var top_opera = "+";
		if (top < 0) {
			var top_opera = "-";
			top = -1 * top;
		}
		topStr = `calc(50% ${top_opera} ${top}px)`;

		var leftStr = '';
		var left_opera = "+";
		if (left < 0) {
			var left_opera = "-";
			left = -1 * left;
		}
		leftStr = `calc(50% ${left_opera} ${left}px)`;
		console.log(topStr, "===========topStr=======");
		console.log(leftStr, "===========leftStr=======");

		if (this.id == "") {
			$(".canvas-container").css({
				left: 'inital',
				right: 100 - changLeft,
				top: topStr,
				transform: "translateY(-50%)"
			});
		}
		else {
			$(".canvas-container").css({
				left: leftStr,
				top: topStr,
				transform: "translate(-50%, -50%)"
			});
		}


	}

	//将自由临摹的字
	selectFreeActiveItem = (evt, item) => {
		evt.preventDefault();
		this.setState({
			freeActiveItem: item
		})
	}




	onImgDragStart = (evt, item) => {
		evt.preventDefault();

		console.log(item.ImageURL);
		var that = this;
		that.setState({
			dragIning: true
		});


		var dt = evt.dataTransfer;
		dt.effectAllowed = "move";
		dt.setData("text/plain", JSON.stringify(item));


		$('.canvas-container').unbind().bind(PageEventType.endEvent, function (evt) {
			console.log(evt, "=======endEvent======");

			if (that.state.dragIning) {

				var evt_pageX = evt.pageX || evt.touches[0].pageX;
				var evt_pageY = evt.pageY || evt.touches[0].pageY;


				var evt_pageX = evt.layerX;
				var evt_pageY = evt.layerY;
				var evt_pageX = evt.x;
				var evt_pageY = evt.y;

				var evt_pageX = evt.layerX;
				var evt_pageY = evt.layerY;


				var url = that.props.baseStore.GetFinalImageUrlForCanvas(item.ImageURL);

				fabric.Image.fromURL(url, function (oImg) {

					oImg.width = oImg._element.width;
					oImg.height = oImg._element.height;

					oImg.top = evt_pageY - 150 * oImg.height / 300;
					oImg.left = evt_pageX - 150 * oImg.width / 300;

					console.log(`${oImg.top}_${oImg.left}`);

					oImg.preserveObjectStacking = true;

					oImg.scaleX = oImg.width / 300;
					oImg.scaleY = oImg.height / 300;

					oImg.crossOrigin = 'anonymous';

					oImg.selectable = true;

					that._canvas.add(oImg);

				});
			}

			console.log("=======endEvent======");

			that.setState({
				// dragIning: false
			});

		}).bind(PageEventType.cancelEvent, function (evt) {

			console.log("=======cancelEvent======");

			that.setState({
				dragIning: false
			});



		})

		$(window).on(PageEventType.endEvent, function (e) {
			that.setState({
				dragIning: false
			});
		})

	}

	selectDragCharDialogClose = () => {




		$(".select_drag_char_dialog").removeClass('rollIn').addClass('rollOut fast');

		setTimeout(() => {
			this.props.createStore.ClearCurrnetWordImgList();
		}, 1000);

	}

	showBgSelect = () => {
		this.setState({
			show_bg_select: !this.state.show_bg_select
		})
	}


	bgImgSelect = (item) => {
		var that = this;
		service.GetFuShiChildListById(item.DirectoryID).then(res => {
			console.log(res, "===========GetShuJiaList========");
			console.log(res.length, "===========list.length========");
			that.setState({
				fu_shi_sub_list: res
			});

		})

	}

	bgImgSubSelect = (item) => {

		var that = this;
		console.log(item, "=========bgImgSubSelect=======");
		Modal.confirm({
			title: '重新选择,将清除画布',
			content: '是否确认操作?',
			okText: '确认',
			cancelText: '取消',
			onOk: function () {


				var url = (that.props.baseStore.getPicInnerStaticPreUrl + item.ImageURL);
				url = that.props.baseStore.GetFinalImageUrlForCanvas(item.ImageURL);
				that._canvas.clear();

				that.setState({
					currenCanvasBgImageURL: url
				});

				that.initCanvas(url);



			}
		});




	}


	saveLinmoWord = () => {
		var that = this;

		console.log(this.state.formData);
		// return;
		service.SaveLinmoWord(this.state.formData).then(res => {


			console.log(res, "saveLinmoWord");
			message.success('保存成功');

			setTimeout(() => {
				that.setState({
					visible: false
				});
				that.props.baseStore.currentWordImgList = [];
				that.props.createStore.ClearCurrnetWordImgList();
				that.canvasClear();
				// that.props.history.push('/entry_04');
			}, 1000);

		});
	}




	showSaveEditModel = () => {

		this._canvas.selection = false;
		this._canvas.getActiveObject();
		this._canvas.renderAll();

		const dataURL = this._canvas.toDataURL({
			format: 'png', // jpeg或png
		});

		var img = new Image();
		img.setAttribute('crossOrigin', 'anonymous');
		img.src = dataURL;

		var formData = this.state.formData;
		formData.ImageURL = dataURL;
		// formData.ImageURL = 'http://www.baidu.com';

		formData.ParentFormatId = this.state.fu_shi_list[this.state.fuShiIndex].DirectoryID;
		formData.ParentFormatName = this.state.fu_shi_list[this.state.fuShiIndex].DirectoryName;
		formData.PageFormatId = this.state.fu_shi_list[this.state.fuShiSubIndex].DirectoryID;
		formData.PageFormatName = this.state.fu_shi_list[this.state.fuShiSubIndex].DirectoryName;

		var JsonStr = this._canvas.toJSON();
		console.log(JsonStr, "============JsonStr=========");
		formData.JsonStr = JSON.stringify(JsonStr);
		// formData.JsonStr="哈哈";
		this.setState({
			show_img_url: dataURL,
			show_img: true,
			visible: true,
			formData: formData
		})


	}

	handleChangeShuJia = (index) => {

		var item = this.state.ShuJiaList[index];

		var formData = this.state.formData;
		formData.CalligrapherId = item.ItemDetailId;
		formData.CalligrapherName = item.ItemName;
		this.setState({
			formData: formData
		});
	}

	handleChangeFuShi = (index) => {

		// var item =this.getSameLevelBgList()[index];

		// var formData = this.state.formData;
		// formData.PageFormatId = item.ItemId;
		// formData.PageFormatName = item.ItemName;
		// this.setState({
		// 	formData: formData
		// });
	}

	handleChangeNum = (value) => {
		var formData = this.state.formData;
		formData.WordNum = value;

		this.setState({
			formData: formData
		});
	}



	handleDirectoryNameChange = (event) => {
		var formData = this.state.formData;
		formData.DirectoryName = event.target.value;
		this.setState({ formData: formData });
	}

	render() {

		let sideClassName = "ShowPage_Side";

		if (this.state.side_show) {
			sideClassName += " toggle_show ";
		}

		if (!this.state.side_show) {
			sideClassName += " toggle_hide ";
		}

		if (this.state.id.length > 0) {
			sideClassName += " no_side_main";
		}

		var sideMainCls = "ShowPage_Side_Main "
		if (this.props.createStore.rightList.length > 5) {
			sideMainCls += " has_scroll_bar";
		}

		console.log(this.props.createStore.rightList, "rightlist");

		return (

			<div className="ShowPage CreatePage page_container  fadeInDown fast" >


				<div className={sideClassName} ref="_side" >


					<div className={sideMainCls} ref="_tool" >

						{
							this.props.createStore.rightList.map((item, index) => {


								var single_container_cls = "single_container ";
								if (this.state.activeRightListIndex == index) {
									single_container_cls = single_container_cls + ' active';
								}

								return (
									<div className={single_container_cls} key={index} onClick={() => this.singleContainClick(item, index)}>
										<div className="single_img_container">
											{/* <img draggable="true" src={this.props.baseStore.GetFinalImageUrl(item.ImageURL)} alt="" onDragStart={(evt) => this.onImgDragStart(evt, item)} /> */}
											<img draggable="true" src={this.props.baseStore.GetFinalImageUrl(item.ImageURL)} alt="" />
										</div>
									</div>
								)
							})
						}


					</div>


					<div className="ShowPage_Tool" ref="_tool" >

						{/* <div className="canvas_can_drag">
							整体拖动
						</div> */}

						<div className="canvas_zoom_out" onClick={() => this.canvasZoomDirect(1)}>
							初始比例
						</div>
						<div className="canvas_zoom_in" onClick={this.canvasZoomIn}>
							比例放大
						</div>
						<div className="canvas_zoom_out" onClick={this.canvasZoomOut}>
							比例缩小
						</div>


						{
							this.state.id == '' && <div className="canvas_clear" onClick={this.canvasClear}>
								清除画布
							</div>
						}

						{
							this.state.id == '' && <div className="canvas_clear" onClick={this.canvasClearSelected}>
								清除选中
							</div>
						}

						{/* <div className="canvas_toggle_bg" onClick={this.canvasChangeBg}>
							切换背景
						</div> */}

						{/* <div className="canvas_create_img" onClick={this.canvasChangeMyMod}>
							模式{this.state.canvasMyMod == 0 ? '展示' : '单字'}{this.state.canvasMyMod}
						</div> */}


						<div className="moveCanvas" onClick={() => this.moveCanvasHandler(1)}>
							向上移动
						</div>
						<div className="moveCanvas" onClick={() => this.moveCanvasHandler(3)}>
							向下移动
						</div>
						<div className="moveCanvas" onClick={() => this.moveCanvasHandler(2)}>
							向左移动
						</div>
						<div className="moveCanvas" onClick={() => this.moveCanvasHandler(4)}>
							向右移动
						</div>



						{/* <div className="canvas_create_img" onClick={this.canvasToImg}>
							生成图片
						</div> */}
						{/* <div className="canvas_create_img" onClick={this.canvasToImg}>
							生成JSON
						</div> */}

						{
							this.state.id == '' && <div className="canvas_create_img" onClick={this.showBgSelect}>
								选择版式
							</div>
						}

						{
							this.state.id == '' && <div className="canvas_create_img" onClick={this.showSaveEditModel}>
								保存创作
							</div>
						}






					</div>

					<div onClick={this.handleClick} className="ShowPage_Tool_Min fixed" ref="_tool_min" >
						<Icon type={this.state.side_show ? "arrow-left" : "arrow-right"} />
					</div>


				</div>



				<div className="ShowPage_Main" >

					<canvas id="canvas" ></canvas>

					{/* <input type="text" /> */}


					{
						this.state.show_bg_select && <div className="bg_select_dialog">

							<div className="bg_select_line bg_select_line_01">
								<div className="bg_select_title">幅式</div>
								<div className="bg_select_content">

									{
										this.state.fu_shi_list.map((item, index) => {
											var cls = "bg_select_each ";
											if (item.active) {
												cls += "active";
											}
											return <div onClick={() => { this.bgImgSelect(item) }} key={index} className={cls}>{item.DirectoryName}</div>
										})
									}

								</div>
							</div>
							<div className="bg_select_line bg_select_line_02">
								<div className="bg_select_title">纸张大小</div>
								<div className="bg_select_content">
									{
										this.state.fu_shi_sub_list.map((item, index) => {
											var cls = "bg_select_each ";
											if (item.active) {
												cls += "active";
											}
											return <div onClick={() => { this.bgImgSubSelect(item) }} key={index} className={cls}>{item.DirectoryName}</div>
										})
									}
								</div>
							</div>

						</div>
					}


				</div>




				{
					this['id'].length == 0 && this.props.createStore.currentWordImgList && this.props.createStore.currentWordImgList.length > 0 && <div className="select_drag_char_dialog  animated rollIn fast  ">
						<div className="sub_img_list">
							{
								this.props.createStore.currentWordImgList.map((item, index) => {
									// onClick={() => { this.selectFreeActiveItem(item) }}
									return <div key={index} className="free_side_each" >
										{/* <img src={item ? this.props.baseStore.GetFinalImageUrl(item.ImageURL) : ''} alt="" /> */}

										{/* <img draggable="true" src={this.props.baseStore.GetFinalImageUrl(item.ImageURL)} alt="" onDragStart={(evt) => this.onImgDragStart(evt, item)} /> */}

										<img draggable="true" src={this.props.baseStore.GetFinalImageUrlForCanvas(item.ImageURL)} alt="" onClick={(evt) => this.selectFreeActiveItem(evt, item)} />



									</div>
								})
							}
						</div>
						<div className="select_drag_char_dialog_close" onClick={this.selectDragCharDialogClose}>
							<Icon type="double-left" />
						</div>
						{
							this.state.activeRightListIndex > 0 ? null : null
						}
					</div>
				}

				{
					this.state.show_img && (<Modal
						// title="生成的图片"
						centered={true}
						width={1200}
						closable={false}
						cancelText="关闭"
						okText="保存"
						visible={this.state.visible}
						// onOk={this.DownLoadImg}
						onOk={this.saveLinmoWord}
						onCancel={() => this.setState({ visible: false })}
					>
						<div className="show_canvas_img_container">

							<div className="show_canvas_img_link">
								{/* download={new Date().getTime()} */}
								<a className="" href={this.state.show_img_url} target="_blank" download={new Date().getTime()}>
									<img className="img_for_show_create_img" src={this.state.show_img_url} alt="" />
								</a>
								<Button className="download_btn" t type="link" onClick={this.DownLoadImg}>图片直接下载</Button>
							</div>
							<div className="right_from">
								<div className="form_line">
									<Input placeholder="名称" allowClear value={this.state.formData.DirectoryName} onChange={this.handleDirectoryNameChange} />
								</div>
								<div className="form_line">
									<Select placeholder="书家" allowClear style={{ width: '100%' }} onChange={this.handleChangeShuJia}  >
										{
											this.state.ShuJiaList.map((item, index) => {
												return <Option key={index} value={index}>{item.ItemName}</Option>
											})
										}
									</Select>

								</div>


								<div className="form_line">
									<Select placeholder="字数" allowClear style={{ width: '100%' }} onChange={this.handleChangeNum}>
										<Option value="1">单字作品</Option>
										<Option value="2">二字作品</Option>
										<Option value="3">三字作品</Option>
										<Option value="4">四字作品</Option>
										<Option value="5">五字作品</Option>
										<Option value="6">六字作品</Option>
										<Option value="7">七字作品</Option>
										<Option value="8">八字作品</Option>
										<Option value="0">多字作品</Option>
									</Select>
								</div>

							</div>

						</div>


					</Modal>)
				}

			</div >
		);


	}
}

export default ShowPage;